<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1; height: 100%"
    element-loading-text="加载中..."
  >
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addData"> 添加说明书 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          clearable
          v-model="name"
          placeholder="关键词搜索"
          class="input-with"
          @keyup.enter="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <div class="table">
      <el-table
        border
        stripe
        resizable
        :data="tableData"
        @selection-change="handleChange"
        ref="tableDom"
        style="position: absolute"
        height="100%"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" />
        <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
        <el-table-column show-overflow-tooltip prop="name" label="说明书名称" min-width="300" />
        <el-table-column
          show-overflow-tooltip
          prop="knowledgeType"
          label="知识库类型"
          min-width="300"
        />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="clickNum" label="点击数" width="100" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column show-overflow-tooltip fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="insView(scope.row)">预览</HLink>
              <HLink @click="insDetail(scope.row)">详细</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  说明书弹窗 -->
    <HModal v-model="addDialog" :width="900">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="dialogLoading" element-loading-text="加载中...">
        <div class="form-text">
          <el-form
            label-width="110"
            ref="formRef"
            :rules="rules"
            :model="form"
            class="form_content"
            @validate="handleFormValidate"
          >
            <el-form-item
              label="说明书名称"
              :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
              prop="name"
            >
              <el-input
                v-model="form.name"
                style="width: 300px"
                clearable
                placeholder="请输入名称"
              />
            </el-form-item>
            <el-form-item label="说明书状态" class="radio_form_item">
              <el-radio-group v-model="form.status">
                <div class="radio_container">
                  <el-radio :value="false">
                    <span class="bg_text">启用</span>
                  </el-radio>
                  <el-radio :value="true">
                    <span class="bg_text">禁用</span>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="所属知识库类型" class="form_item">
              <KnowledgeMultiple
                ref="knowledgeMultipleRef"
                :oldKnowledgeTypeVo="oldKnowledgeTypeVo"
              />
            </el-form-item>
            <el-form-item label="封面" class="form_item">
              <div class="upload-card">
                <el-upload
                  accept="image/*"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="uploadinsFile"
                >
                  <el-image style="width: 100px; height: 100px" :src="insImage" fit="contain">
                    <template #error>
                      <div class="image-slot">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                </el-upload>
              </div>
            </el-form-item>
            <WangEdior :all_data="ediorData" ref="wangEdior" />
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          is-modal
          type="error"
          v-show="dialogTitle === '编辑说明书'"
          @click="changeAll(4)"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>

    <!-- 说明书预览弹窗 -->
    <el-dialog
      v-model="viewDialog"
      title="说明书预览"
      width="800px"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="view-dialog"
      top="8vh"
    >
      <div v-loading="dialogLoading" element-loading-text="加载中...">
        <div class="title flex-justify-between">
          <span class="name">{{ form.name }}</span>
          <p>更新时间：{{ upTime }}</p>
        </div>
        <div class="img flex-center">
          <el-image style="width: 600px; height: 250px" :src="insImage" fit="contain">
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
        <div class="content">
          <div class="left">内容</div>
          <div class="text" v-html="form.content" v-if="form.content"></div>
          <el-empty description="暂无内容..." v-else style="width: 100%" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import {
    Search,
    Plus,
    Picture as IconPicture,
    Delete,
    Warning,
    CircleCheck,
    ArrowDown,
  } from '@element-plus/icons-vue'
  import { ref, reactive, onMounted, markRaw, h } from 'vue'
  import { ElDivider, ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import type { UploadFile, UploadProps, FormInstance } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import WangEdior from '@/components/WangEdior/index.vue'
  import KnowledgeMultiple from '@/components/Knowledge/knowledgeMultiple.vue'
  import { knowledgeAnnexUpload, deleteFile } from '@/api/upload'
  import { instrList, instrSave, instrInfo, instrDisable, instrDelete } from '@/api/knowledge'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import { HModal } from '@/components/common'

  /**
   * 表单验证结果
   */
  const formValidateResult = ref(false)

  /**
   * 表单验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value = isValid
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    formValidateResult.value = true
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const loading = ref(false)

  const name = ref('') // 名称
  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom
  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const addDialog = ref(false)
  const viewDialog = ref(false)
  const dialogTitle = ref('')
  const dialogLoading = ref(false)
  const upTime = ref('')

  const insImage = ref()
  const insFile = ref()

  const formRef = ref<FormInstance>()
  const knowledgeMultipleRef = ref() // 知识库类型组件
  const oldKnowledgeTypeVo = ref([])

  const form = reactive({
    id: null,
    name: '',
    status: false,
    content: '',
    image: '',
    delRelationIds: [],
    knowledgeTypeVos: [],
  })

  const wangEdior = ref()
  const ediorData = ref({ content: '', type: 'knowledge' })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入说明书名称', trigger: ['blur', 'change'] }],
  })

  onMounted(() => {
    getList()
  })

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    const data = {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
    await instrList(data).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格勾选数据
  const selecttion = ref([])
  const handleChange = (val: any) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 添加说明书
  const addData = async () => {
    dialogTitle.value = '添加说明书'
    addDialog.value = true

    insImage.value = ''
    insFile.value = ''
    form.content = ''
    form.id = null
    form.image = ''
    form.name = ''
    form.status = false
    setTimeout(() => {
      wangEdior.value.clearValue()
    }, 100)
  }

  // 编辑说明书
  const insDetail = async (obj) => {
    dialogTitle.value = '编辑说明书'
    insFile.value = ''
    addDialog.value = true
    dialogLoading.value = true
    await instrInfo(obj.id).then((res) => {
      const data = res.data.data.row
      form.id = data.id
      form.name = data.name
      form.content = data.content
      ediorData.value = { content: data.content, type: 'knowledge' }
      form.image = data.image
      insImage.value = data.image
      form.status = data.status
      oldKnowledgeTypeVo.value = data.knowledgeTypeVos
    })
    dialogLoading.value = false
  }

  // 获取说明书图片地址
  const uploadinsFile: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    if (!uploadFile.raw.type.includes('image')) {
      ElMessage.error('只能上传图片')
      return false
    }
    if (uploadFile.raw.size / 1024 / 1024 > 50) {
      ElMessage.error('图片大小不能超过50M!')
      return false
    }
    insFile.value = uploadFile.raw
    insImage.value = window.URL.createObjectURL(uploadFile.raw)
  }

  // 保存的方法
  const saveMethod = async (method, data) => {
    form.knowledgeTypeVos = knowledgeMultipleRef.value.getKnowledgeSelectVal().value
    form.delRelationIds = knowledgeMultipleRef.value.getDeleteKnowledgeSelectVal().value
    dialogLoading.value = true
    // 上传图片
    if (insFile.value) {
      const files = []
      files.push(insFile.value)
      if (files.length != 0) {
        await knowledgeAnnexUpload(files).then((res) => {
          if (insImage.value.startsWith('blob') && form.image != '') {
            deleteFile([form.image]).then()
          }
          data.image = res.data.data.rows[0]
        })
      }
    }
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialogLoading.value = false
        getList()
        onClose()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        dialogLoading.value = false
        return
      }
    })
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        form.content = wangEdior.value.getValue()
        wangEdior.value.getDeleteImages()
        saveMethod(instrSave, form)
      }
    })
  }

  // 预览说明书
  const insView = async (obj) => {
    viewDialog.value = true
    dialogLoading.value = true
    await instrInfo(obj.id).then((res) => {
      form.name = res.data.data.row.name
      form.content = res.data.data.row.content
      upTime.value = obj.updateTime
      insImage.value = res.data.data.row.image
    })
    dialogLoading.value = false
  }

  // 修改状态的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的说明书`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的说明书?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', instrDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', instrDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', instrDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', instrDelete, [form.id], 3, 1)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import './AddManual.scss';
</style>
